package com.db.Dao.impl;

import com.db.Dao.UserDao;
import com.db.entity.User;
import com.db.util.DButils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class UserDaoImpl implements UserDao {
    @Override
    public User login(User user){

        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user1 = null;

        try{
            conn = DButils.getConnection();

            String sql = "select id,username,password from t_user where username = ? and password = ?";
            pstm = conn.prepareStatement(sql);

            pstm.setString(1,user.getUsername());
            pstm.setString(2,user.getPassword());

            rs = pstm.executeQuery();
            if(rs.next()){
                Integer id = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");

                user1 = new User(id,username,password);
            }



        }catch( Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);

        }finally{
            DButils.close(null,pstm,rs);
        }

        return user1;
    }

    @Override
    public User selectUserByUsername(User user)  {
        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user1 = null;

        try{
            conn = DButils.getConnection();
            String sql = "select id,username,password from t_user where username = ?";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1,user.getUsername());
            rs = pstm.executeQuery();
            if( rs.next() ){
                Integer userId = rs.getInt("id");
                String username = rs.getString("username");
                String password = rs.getString("password");

                user1 = new User(userId,username,password);
            }


        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);

        }finally{
            DButils.close(null,pstm,rs);

        }


        return user1;
    }

    @Override
    public void insertUser(User user){
        Connection conn = null;
        PreparedStatement pstm = null;

        try{
            conn = DButils.getConnection();
            String sql = "insert into t_user values(null,?,?)";
            pstm = conn.prepareStatement(sql);
            pstm.setString(1,user.getUsername());
            pstm.setString(2,user.getPassword());
            pstm.executeUpdate();

        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);

        }finally{
            DButils.close(null,pstm,null);

        }

    }
}
